<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>用户管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="/lib/font-awesome-4.7.0/css/font-awesome.min.css" media="all">
    <link rel="stylesheet" href="/css/public.css" media="all">
</head>
<body>
<div class="layuimini-container" id="app">
    <div class="layuimini-main">
        <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
            <legend>服分组{{detail.id?'编辑':'添加'}}</legend>
        </fieldset>
        <form class="layui-form" action="javascript:;" lay-filter="formOne">
            <div class="layui-form-item">
                <label class="layui-form-label">分组名称</label>
                <div class="layui-input-block">
                    <input type="text" v-model="detail.name" lay-verify="title" autocomplete="off" placeholder="请输入" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">选择渠道</label>
                <div class="layui-input-block">
                    <input type="checkbox" class="layui-input" v-for="item in channels" :title="item.name" lay-filter="channel"
                           name="channelId[]" :value="item.id" :checked="channelIsChecked(item.id)" />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">选择包</label>
                <div class="layui-input-block" id="temp-package-box">

                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">选择模版配置</label>
                <div class="layui-input-block">
                    <input type="checkbox" class="layui-input" v-for="item in configs" :title="item.name" lay-filter="channel"
                           name="configId[]" :value="item.id" :checked="configsChecked(item.id)" />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">活动排期表配置</label>
                <div class="layui-input-block">
                    <input type="radio" class="layui-input" v-for="item in gameVersion" :title="item.name" lay-filter="gameVersion"
                           name="gameVersionId" :value="item.id" :checked="configsChecked(item.id)" />
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit="" lay-filter="submit">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>
</div>
<script src="/lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="/js/lay-config.js?v=1.0.4" charset="utf-8"></script>
<script src="/js/common.js?v=5" charset="utf-8"></script>
<script id="tempCheckboxList" type="text/html">
    {{# layui.each(d.tempPackages,function(index,item){ }}
    <input type="checkbox" class="layui-input" title="{{item.package_no}} - {{item.description}}" name="packageId[]"
           value="{{item.id}}" {{ d.checkedIds.indexOf(item.id)!==-1 ? 'checked':'' }} />
    {{# })  }}
</script>
<script>
    from = null;
    Id = urlParam('id')
    initChannels = []; //编辑的时候初始化的渠道数组
    var gameVersion = getEnum('gameVersion')

    new Vue({
        el:"#app",
        data:{
            channels:[], //显示的候选渠道
            configs:[], //显示的候选渠道
            packages:[], //所有的包
            tempPackages:[],//临时选择的包
            packageCheckedIds:[],
            detail:{
                id:null,
                name:null,
                channels:[],
                packages:[],
                configs:[]
            }
        },
        methods:{
            getValuesFromForm:function(keyStr){
                var obj = form.val('formOne');
                var values = [];
                for(var key in obj) {
                    var val = obj[key];
                    if (key.indexOf(keyStr)!==-1){
                        values.push(parseInt(val))
                    }
                }
                return values;
            },
            channelIsChecked:function (id) {
                var _this = this;
                var checked = false;

                _this.detail.channels.forEach(x=>{
                    if (x.id === id) {
                        checked = true;
                    }
                })
                return checked;
            },

            configsChecked:function (id) {
                var _this = this;
                var checked = false;

                _this.detail.configs.forEach(x=>{
                    if (x.id === id) {
                        checked = true;
                    }
                })
                return checked;
            }
        },
        updated:function(){
            form.render();
        },
        mounted:function(){
            var _this = this;
            layui.use(['form','jquery','laytpl'], function () {
                form = layui.form;
                var layer = layui.layer ,$ = layui.jquery,laytpl = layui.laytpl;

                //渠道列表
                $.get("/admin/gameChannel/paginate",{page:1,limit:9999},function(res){
                    _this.channels = res.data;
                });
                
                //模版
                $.get("/admin/configGroup/paginate",{page:1,limit:9999},function(res){
                    _this.configs = res.data;
                });
                //包列表
                $.get("/admin/gamePackage/paginate",{page:1,limit:9999},function(res){
                    _this.packages = res.data;
                    if (Id){
                        $.get('/admin/serverGroup/'+Id,{},function(res){
                            // 复制数据并清理 channels 中的 content 字段
                            _this.detail = JSON.parse(JSON.stringify(res.data));
                            
                            // 精简 channels 数据，只保留必要的字段
                            if (_this.detail.channels && Array.isArray(_this.detail.channels)) {
                                _this.detail.channels = _this.detail.channels.map(channel => ({
                                    id: channel.id
                                    // 只保留 id 字段，删除其他所有字段
                                }));
                            }
                            
                            // 精简 packages 数据，只保留必要的字段
                            if (_this.detail.packages && Array.isArray(_this.detail.packages)) {
                                _this.detail.packages = _this.detail.packages.map(pkg => ({
                                    id: pkg.id
                                    // 只保留 id 字段，删除其他所有字段
                                }));
                            }
                            
                            // 精简 configs 数据，只保留必要的字段
                            if (_this.detail.configs && Array.isArray(_this.detail.configs)) {
                                _this.detail.configs = _this.detail.configs.map(config => ({
                                    id: config.id
                                    // 只保留 id 字段，删除其他所有字段
                                }));
                            }
                            
                            console.log('配置数',_this.detail);
                            var channels = res.data.channels;
                            var packages = res.data.packages;
                            initChannels = JSON.parse(JSON.stringify(channels));
                            if (_this.detail.gameVersionId) {
                                $('input[name="gameVersionId"][value="' + _this.detail.gameVersionId + '"]').prop('checked', true);
                                form.render('radio'); // 重新渲染单选框
                            }
                            var channelIds = []
                            channels.forEach(x=>{
                                channelIds.push(x.id)
                            })

                            showPackagesByChannelIds(channelIds)
                            var packageCheckedIds = [];
                            packages.forEach(x=>{
                                packageCheckedIds.push(x.id)
                            })
                            _this.packageCheckedIds = packageCheckedIds;
                        });
                    }
                });

                function showPackagesByChannelIds(channelIds) {
                    $('#temp-package-box').html('')
                    $.get('/admin/gameChannel/getByIds',{ids:channelIds},function(res){
                        var channels = res.data;
                        var packages = []
                        channels.forEach(channel=>{
                            channel.packages.forEach(x=>{
                                packages.push(x)
                            })
                        })
                        _this.packages = packages;
                        var html = laytpl($('#tempCheckboxList').prop("innerHTML")).render({
                            tempPackages: packages,
                            checkedIds: _this.packageCheckedIds, //默认选中
                        })
                        $('#temp-package-box').html(html)
                        form.render();
                    })
                }

                form.on('checkbox(channel)',function(data){
                    var channelIds = _this.getValuesFromForm("channelId");
                    showPackagesByChannelIds(channelIds);
                })

                form.on('checkbox(gameVersion)',function(data){
                    var channelIds = _this.getValuesFromForm("channelId");
                    showPackagesByChannelIds(channelIds);
                })

                
                
                //监听提交
                form.on('submit(submit)', function (data) {
                    // 创建副本并再次清理 content 字段
                    var formData = JSON.parse(JSON.stringify(_this.detail));
                    
                    // 提交前精简数据，只保留必要字段
                    if (formData.channels && Array.isArray(formData.channels)) {
                        formData.channels = formData.channels.map(channel => ({
                            id: channel.id
                        }));
                    }
                    
                    if (formData.packages && Array.isArray(formData.packages)) {
                        formData.packages = formData.packages.map(pkg => ({
                            id: pkg.id
                        }));
                    }
                    
                    if (formData.configs && Array.isArray(formData.configs)) {
                        formData.configs = formData.configs.map(config => ({
                            id: config.id
                        }));
                    }
                    
                    var channelIds = _this.getValuesFromForm('channelId[');
                    var packageIds = _this.getValuesFromForm('packageId[');
                    var configId = _this.getValuesFromForm('configId[');
                    var gameVersionId = $('input[name="gameVersionId"]:checked').val();

                    
                        // 检查 configId 的选中数目
                    if (configId.length > 1) {
                      layer.msg('只能选择一个模版配置'); // 使用 layui 的消息提示
                    return false; // 阻止表单提交
                      }
                    formData.configId=configId;
                    formData.channelIds = channelIds;
                    formData.packageIds = packageIds;
                    formData.gameVersionId = gameVersionId;

                    if (Id){ //eidt
                        formData._method = 'put';

                        var willDeleteChannels = [];

                        initChannels.forEach(x=>{
                            if ( channelIds.indexOf(x.id) === -1 ) {
                                willDeleteChannels.push(x)
                            }
                        })

                        function postIt(){

                            $.post('/admin/serverGroup/'+Id,formData,function(res){
                                if (res.code===0){
                                    layer.msg('success',{icon:6,time:500},function(){
                                        parent.location.reload();//父页面刷新
                                    })
                                } else {
                                    layer.msg(res.msg,{icon:5})
                                }
                            })
                        }

                        if (willDeleteChannels.length > 0 ) {

                            var text = '';
                            willDeleteChannels.forEach(x=>{
                                text += `,${x.id}-${x.name}`
                            })
                            text = text.substring(1);
                            layer.confirm(`此次编辑删除了该分组下的 ${text} ，请确认`,{icon:3,title:"提示"},function(){
                                postIt();
                            })
                        } else {
                            postIt();
                        }

                    } else { //add
                        $.post('/admin/serverGroup/add',formData,function(res){
                            if (res.code===0){
                                layer.msg('success',{icon:6,time:500},function(){
                                    parent.location.reload();//父页面刷新
                                })
                            } else {
                                layer.msg(res.msg,{icon:5})
                            }
                        })
                    }

                    return false;
                });

            });

        }
    })
</script>

</body>
</html>